package com.gxa.servlet.staffservlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.pojo.Result;
import com.gxa.pojo.staff.UserStaff;
import com.gxa.service.staffservice.StaffService;
import com.gxa.service.staffservice.impl.StaffServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/cancelClockServlet")
public class CancelClockServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        //因为request.getreader（）方法只能读一次，采样下面几行代码
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuilder json = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            json.append(inputStr);
        }
        String jsonString = json.toString(); //这是将json转化为字符串的形式
       // 将json字符串转化对象
        ObjectMapper objectMapper = new ObjectMapper();
        UserStaff user = objectMapper.readValue(jsonString, UserStaff.class);
        int staff_id = user.getStaff_id();
        StaffService staffService = new StaffServiceImpl();
        Boolean cancleclock = staffService.cancleclock(staff_id);
        //返回状态（成功与否）
        Map<String,Object> map = new HashMap<>();
        String flag =null;
        if (cancleclock){
            map.put("result", Result.ok("success",user));
            flag=objectMapper.writeValueAsString(map);
        }else {
            map.put("result",Result.error());
            flag=objectMapper.writeValueAsString(map);
        }
        PrintWriter writer = response.getWriter();
        writer.write(flag); //响应状态
        writer.flush();     //刷新流
        writer.close();     //关闭流
        streamReader.close(); //关闭
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
